package com.itzz.spring_zhoneHeng.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author liuweibo
 * @date 2023/6/12
 */

@Component
public class Upload {
//    @Bean
    @Value("${path.loadPath}")
    String loadPath;

    @Value("${path.urlPath}")
    String urlPath;

    public  String upLoad(MultipartFile file){
        try {
            //获取图片名字
            String fileName = file.getOriginalFilename();
            if (fileName==null){
                return null;
            }
            //张三.png
            //获取文件扩展名  .png        截取(直接截取到末尾)      返回下标
            String ref = fileName.substring(fileName.lastIndexOf("."));
            //给图片重命名 随机数16进制
            fileName= UUID.randomUUID().toString()+ref;
            //将图片保存在tomcat本地地址中
            //String path=req.getServletContext().getRealPath("/img/"+fileName);
            //将图片保存到本地D盘中
            String path=loadPath+fileName;
            //D://Workspace403/img/
            //http://localhost:8080/servlet_mvc/
            //http://localhost:8080/servlet_mvc/img/
            file.transferTo(new File(path));
            String path2=urlPath+fileName;
            return  path2;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}